package com.boot.webflux.security.example2.module.controller;

import com.boot.webflux.security.example2.module.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import sun.plugin.liveconnect.SecurityContextHelper;

@RestController
@RequestMapping("/role")
@Slf4j
public class TestController {
    @PreAuthorize("hasRole('user')")
    @PostMapping("/query")
    public Mono<String> test1(){
        log.info("-------test/a---------");
        return Mono.just("你好");
    }
    @PutMapping("/update")
    public Mono<String> test2(){
        log.info("-------test/b---------");

        return Mono.just("你好");
    }
    @PostMapping("/test")
    public Mono<SysUser> test3(){
        return ReactiveSecurityContextHolder.getContext()
                .switchIfEmpty(Mono.error(new IllegalStateException("ReactiveSecurityContext is empty")))
                .map(SecurityContext::getAuthentication)
                .map(Authentication::getPrincipal)
                .cast(SysUser.class);
    }
}
